package com.dingwei.superiordiary.mvp.presenter;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import com.dingwei.superiordiary.R;
import com.dingwei.superiordiary.base.MyBaseBean;
import com.dingwei.superiordiary.bean.FailsBean;
import com.dingwei.superiordiary.bean.ReviewListBean;
import com.dingwei.superiordiary.custom.myCallback;
import com.dingwei.superiordiary.mvp.view.Contract;
import com.dingwei.superiordiary.ui.activity.LoginActivity;
import com.lihao.baselibrary.base.BaseActivity;
import com.lihao.baselibrary.base.URLS;
import com.lihao.baselibrary.base.basePresenter;
import com.lihao.baselibrary.utils.ScreenUtils;

import org.xutils.http.RequestParams;
import org.xutils.x;

import static com.scwang.smartrefresh.layout.util.DensityUtil.dp2px;

/**
 * Created by lihao on 2017/9/12.
 */

public class ReviewListPresenter extends basePresenter {

    private Contract.ReviewListView reviewListView;
    private Dialog bottomDialog;
    private PopupWindow popupWindow;
    public ReviewListPresenter(Contract.ReviewListView view) {
        super(view);
        this.reviewListView = view;
    }

    public void showEvaluationDialog(final String id, final String pid) {
        View view = LayoutInflater.from(BaseActivity.context).inflate(R.layout.dialog_evaluation, null);
        final EditText etEvaluation = (EditText) view.findViewById(R.id.et_evaluation);
        Button btnAddComment = (Button) view.findViewById(R.id.btn_add_comment);
        btnAddComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                saveComment(id,pid,etEvaluation.getText().toString());
                bottomDialog.dismiss();
            }
        });
        view.measure(0, 0);
        bottomDialog = new Dialog(BaseActivity.context, R.style.Theme_Light_Dialog);
        bottomDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        bottomDialog.setContentView(view);
        Window dialogWindow = bottomDialog.getWindow();
        //设置dialog在屏幕底部
        dialogWindow.setGravity(Gravity.BOTTOM);
        //设置dialog弹出时的动画效果，从屏幕底部向上弹出
        dialogWindow.setWindowAnimations(R.style.dialogstyle);
        dialogWindow.getDecorView().setPadding(0, 0, 0, 0);
        //获得window窗口的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        //设置窗口宽度为充满全屏
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        //设置窗口高度为包裹内容
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //将设置好的属性set回去
        dialogWindow.setAttributes(lp);
        bottomDialog.show();
    }


    private void saveComment(String id, final String pid, String content) {
        RequestParams rp = new RequestParams(URLS.HOST+URLS.PRODUCT_SAVE_COMMENT);
        rp.addBodyParameter("id",id);
        rp.addBodyParameter("pid",pid);
        rp.addBodyParameter("content",content);
        rp.addBodyParameter("sessionid",BaseActivity.value.getToken());

        x.http().post(rp, new myCallback(BaseActivity.context,MyBaseBean.class) {
            @Override
            public void back(MyBaseBean baseBean, String result) {
                showToast(baseBean.message);
                reviewListView.saveCommentSuccess();
            }

            @Override
            public void fail(FailsBean baseBean, String result) {

            }
        });
    }


    public void showSortPopupWindow(View tvShow) {
        View view = LayoutInflater.from(BaseActivity.context).inflate(R.layout.dialog_sort, null);
        LinearLayout llhot = (LinearLayout) view.findViewById(R.id.ll_hot);
        LinearLayout llTime = (LinearLayout) view.findViewById(R.id.ll_time);
        LinearLayout llBg = (LinearLayout) view.findViewById(R.id.ll_bg);
        llhot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                reviewListView.SetHotSort();
            }
        });
        llTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                reviewListView.SetTimeSort();
            }
        });
        popupWindow = new PopupWindow(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
        popupWindow.setContentView(view);
        popupWindow.setFocusable(true);
        popupWindow.setTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(true);
        int windowPos[] = calculatePopWindowPos(tvShow, view,llBg);
        popupWindow.showAtLocation(view, Gravity.TOP | Gravity.START, windowPos[0], windowPos[1]);
        backgroundAlpha(0.4f);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1);
            }
        });
    }



    private void backgroundAlpha(float f) {
        WindowManager.LayoutParams lp = BaseActivity.context.getWindow().getAttributes();
        lp.alpha = f;
        BaseActivity.context.getWindow().setAttributes(lp);
    }
    /**
     * 计算出来的位置，y方向就在anchorView的上面和下面对齐显示，x方向就是与屏幕右边对齐显示
     * 如果anchorView的位置有变化，就可以适当自己额外加入偏移来修正
     *
     * @param anchorView  呼出window的view
     * @param contentView window的内容布局
     * @return window显示的左上角的xOff, yOff坐标
     */
    private int[] calculatePopWindowPos(final View anchorView, final View contentView,LinearLayout llBg) {
        final int windowPos[] = new int[2];
        final int anchorLoc[] = new int[2];
        // 获取锚点View在屏幕上的左上角坐标位置
        anchorView.getLocationOnScreen(anchorLoc);
        final int anchorHeight = anchorView.getHeight();
        // 获取屏幕的高宽
        final int screenHeight = ScreenUtils.getScreenHeight(anchorView.getContext());
        final int screenWidth = ScreenUtils.getScreenWidth(anchorView.getContext());
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        // 计算contentView的高宽
        final int windowHeight = contentView.getMeasuredHeight();
        final int windowWidth = contentView.getMeasuredWidth();
        // 判断需要向上弹出还是向下弹出显示
        final boolean isNeedShowUp = (screenHeight - anchorLoc[1] - anchorHeight < windowHeight);
        if (isNeedShowUp) {
            windowPos[0] = screenWidth - windowWidth;
            windowPos[1] = anchorLoc[1] - windowHeight;
            llBg.setPadding(0, 0, 0, dp2px(10));
            llBg.setBackgroundResource(R.drawable.pic2t);
        } else {
            llBg.setPadding(0, dp2px(10), 0, 0);
            llBg.setBackgroundResource(R.drawable.pic1j);
            windowPos[0] = screenWidth - windowWidth;
            windowPos[1] = anchorLoc[1] + anchorHeight;
        }
        return windowPos;
    }

    public void initData(String id,int page, int type, String status,final boolean isRefresh,boolean isShowDialog) {

        RequestParams rp = new RequestParams(URLS.HOST+URLS.PRODUCT_COMMENT_LIST);
        rp.addBodyParameter("page",page+"");
        rp.addBodyParameter("type",type+"");
        rp.addBodyParameter("type",type+"");
        rp.addBodyParameter("id",id);
        if (!TextUtils.isEmpty(status)){
            rp.addBodyParameter("status",status);
        }

        x.http().post(rp, new myCallback(BaseActivity.context, ReviewListBean.class,isShowDialog,rp) {
            @Override
            public void back(MyBaseBean baseBean, String result) {
                ReviewListBean bean = (ReviewListBean) baseBean;
                if (isRefresh){
                    reviewListView.OnRefresh(isRefresh,bean);
                }else {
                    reviewListView.OnLoadMore(isRefresh,bean);
                }
            }

            @Override
            public void fail(FailsBean baseBean, String result) {
                reviewListView.OnFail();
            }
        });

    }

    public void like(String id) {
        if (!BaseActivity.value.getIsLogin()){
            Intent intent = new Intent(BaseActivity.context,LoginActivity.class);
            BaseActivity.context.startActivity(intent);
            return;
        }
        RequestParams rp = new RequestParams(URLS.HOST+URLS.PRODUCT_LIKES);
        rp.addBodyParameter("id",id);
        rp.addBodyParameter("sessionid",BaseActivity.value.getToken());

        x.http().post(rp, new myCallback(BaseActivity.context, MyBaseBean.class) {
            @Override
            public void back(MyBaseBean baseBean, String result) {
                showToast("点赞成功");
                reviewListView.LikeSuccess();
            }

            @Override
            public void fail(FailsBean baseBean, String result) {
            }
        });
    }

    public void commentLike(String id, final int position) {
        if (!BaseActivity.value.getIsLogin()){
            Intent intent = new Intent(BaseActivity.context,LoginActivity.class);
            BaseActivity.context.startActivity(intent);
            return;
        }
        RequestParams rp = new RequestParams(URLS.HOST+URLS.PRODUCT_LIKES_COMMENT);
        rp.addBodyParameter("id",id);
        rp.addBodyParameter("sessionid",BaseActivity.value.getToken());

        x.http().post(rp, new myCallback(BaseActivity.context, MyBaseBean.class) {
            @Override
            public void back(MyBaseBean baseBean, String result) {
                showToast("点赞成功");
                reviewListView.commentLikeSuccess(position);
            }

            @Override
            public void fail(FailsBean baseBean, String result) {
            }
        });
    }
}
